const axios = require('axios');
const websocket = require("./websocket")
const WebSocket = require('ws');
const pako = require('pako');
const vm = require('vm');
const dataHandler = require("./data_handler")
class Titan007 {

    constructor() {
        this.baseUrl = "https://live.titan007.com";
        this.A = []; // 用于存储 bfdata_ut.js 中的 A 变量
        this.wsStatus = false; // WebSocket 状态
        this.headers = {
            'accept': '*/*',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'cache-control': 'no-cache',
            'pragma': 'no-cache',
            'priority': 'u=0, i',
            'sec-ch-ua': '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
            'Referer': 'https://live.titan007.com/index2in1.aspx?id=3',
            'Referrer-Policy': 'unsafe-url'
        };
        this.T = {}; // 用于存储 alias3.txt 中的内容
    }


    async createWS() {
        let me = this;
        axios.get(`https://livestatic.titan007.com/vbsxml/bfdata_ut.js?r=007${Date.parse(new Date())}`, {
            headers: this.headers
        }).then(res => {
            if (res.data) {
                // 处理 bfdata_ut.js 的内容
                const scriptContent = res.data;
                // 执行脚本内容
                const context = {
                    A: null, // 用于接收脚本中赋值的变量
                    ShowBf: function () { },
                };
                vm.createContext(context);
                vm.runInContext(scriptContent, context);
                me.A = context.A; // 将 A 赋值给 Titan007 实例的属性 
                const url = `https://livestatic.titan007.com/vbsxml/alias3.txt?r=007${Date.parse(new Date())}`;
                axios.get(url, { headers: this.headers }).then(response => {
                    var t_alias = response.data;
                    var nameArr = new Array();
                    nameArr = t_alias.split(',');
                    for (var i = 0; i < nameArr.length; i++) {
                        var nameTemp = nameArr[i].split('^');
                        me.T[nameTemp[0] + "_" + nameTemp[1]] = [nameTemp[2]];
                    }
                }).catch(error => {
                    console.error('请求出错：', error);
                });
                if (me.wsStatus) {
                    return;
                }
                axios.get("https://live.titan007.com/commoninterface", {
                    headers: {
                        "accept": "*/*",
                        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
                        "cache-control": "no-cache",
                        "pragma": "no-cache",
                        "priority": "u=0, i",
                        "sec-ch-ua": "\"Microsoft Edge\";v=\"137\", \"Chromium\";v=\"137\", \"Not/A)Brand\";v=\"24\"",
                        "sec-ch-ua-mobile": "?0",
                        "sec-ch-ua-platform": "\"Windows\"",
                        "sec-fetch-dest": "empty",
                        "sec-fetch-mode": "cors",
                        "sec-fetch-site": "same-origin",
                        "x-forwarded-for": "1.52.247.16",
                        "cookie": "detailCookie=null; Hm_lvt_00f9d0d89fa07b7fd6ba48e30617e8ad=1750172236; bfWin007FirstMatchTime=2025,5,20,08,00,00; win007BfCookie=0^0^1^1^1^1^1^0^0^0^0^0^1^1^1^1^0^0^1^0",
                        "Referer": "https://live.titan007.com/index2in1.aspx?id=3",
                        "Referrer-Policy": "unsafe-url"
                    }
                }).then(res => {
                    console.log("响应内容：", res.data);
                    if (res.data) {
                        let token = encodeURIComponent(res.data);
                        let url = `wss://live.titan007.com/stream?channels=change_ut_xml,ch_goal3_xml2&token=${token}`
                        let ws = new WebSocket(url, {
                            headers: {
                                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0",
                                "Cookie": "detailCookie=null; Hm_lvt_00f9d0d89fa07b7fd6ba48e30617e8ad=1750172236; bfWin007FirstMatchTime=2025,5,20,08,00,00; win007BfCookie=0^0^1^1^1^1^1^0^0^0^0^0^1^1^1^1^0^0^1^0; FS007Filter=1^0^_304_232_1418_2422045_358_2301007_2502744_415395_59358_436386_41_5963361_87_7721958_1366_139419_193_616375_10731667_423377_1029483_481558_1063347_12552679_917381_14501580_14531948_1043566_453771_14613244_14613245_1470_1472_1551_1556_1590_1748_1772_2113_2124_2151_2196_22533044_23342881_2344_2355_25353037_2536_2627_2653_3812993_10473130_1076568_1083_1358_1481_1553_2174_476605_10771661_448239_802403_1457_1477_1482_2343_2371_2378_14281431_15892883_14073229_14073230_215_13463213_780449_459811_455684_1517_1499_1522_1526_611896_1562_2101_^0"
                            }
                        });
                        ws.onopen = () => {
                            global.log("TITAN WebSocket连接已打开");
                            me.wsStatus = true; // 设置 WebSocket 状态为已连接
                        };
                        ws.onmessage = (event) => {
                            try {
                                const jsonStr = pako.inflate(new Uint8Array(event.data), { to: 'string' });
                                const jsonObj = JSON.parse(jsonStr);
                                if (jsonObj.change_ut_xml) {
                                    me.zqScoreChange(jsonObj.change_ut_xml);
                                }
                            } catch (e) {
                                global.log("TITAN  解析数据错误:", e);
                            }
                        };
                        ws.onerror = (error) => {
                            global.log("TITAN WebSocket错误");
                        };
                        ws.onclose = () => {
                            global.log("TITAN WebSocket连接已关闭");
                            me.wsStatus = false;
                            setTimeout(() => {
                                me.createWS()
                            }, 3000); // 设置超时时间为 5 秒
                        };
                    }
                }).catch(err => {
                    console.error("请求失败：", err.message);
                });
            }

        }).catch(err => {
            console.error("获取 bfdata_ut.js 失败：", err.message);
        });

        setTimeout(() => {
            me.createWS()
        }, 1000 * 60 * 10); // 设置超时时间为 5 秒
    }

    async zqScoreChange(data) {
        try {
            var dataList = data.split("!");
            var D = new Array();
            var matchindex
            for (var i = 0; i < dataList.length; i++) {
                D = dataList[i].split("^");
                matchindex = await this.getDataIndex(D[0]);
                //红牌变化了
                if (this.A[matchindex] && (D[6] != this.A[matchindex][18] || D[7] != this.A[matchindex][19])) {
                    global.log("红牌消息：" + data);
                    let key1 = this.T[this.A[matchindex][37] + "_" + 3]
                    let key2 = this.T[this.A[matchindex][38] + "_" + 3];
                    if (!key1 || !key2) {
                        global.log("1 : " + this.A[matchindex][37])
                        global.log("2 : " + this.A[matchindex][38])
                        global.log("从titan007获取皇冠比赛名称失败:")
                        global.log(JSON.stringify(this.T))
                    }
                    dataHandler.red_card_event({
                        home: key1,
                        away: key2,
                        redCardCount: D[6],
                        redCardOld: this.A[matchindex][18],
                    });
                    // TODO 处理红牌变化
                    global.log(`1红牌变化: [${key1} v ${key2}] ${this.A[matchindex][18]} --> ${D[6]}`);
                    global.log(`2红牌变化: [${this.A[matchindex][5]} v ${this.A[matchindex][8]}] ${this.A[matchindex][18]} --> ${D[6]}`);

                    this.A[matchindex][18] = D[6];
                }
            }
        } catch (e) { console.log(e); }
    }

    async getDataIndex(sId) {
        var i = 1;
        for (; i < this.A.length; i++) {
            if (this.A[i][0] == sId)
                break;
        }
        return i;
    }

}
module.exports = Titan007;

// const titan007 = new Titan007();
// titan007.createWS(); // 调用方法创建 WebSocket 连接